package com.gambi.tapestry.services.gwt;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;

import org.apache.tapestry5.services.ComponentEventResultProcessor;
import org.apache.tapestry5.services.RequestGlobals;

import com.gambi.tapestry.utils.GWTBoolean;
import com.gambi.tapestry.utils.GWTNull;
import com.gambi.tapestry.utils.GWTVoid;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;

public class GWTComponentEventEncryptedResultProcessor implements ComponentEventResultProcessor {

	private final RequestGlobals requestGlobals;

	public GWTComponentEventEncryptedResultProcessor(RequestGlobals requestGlobals) {
		this.requestGlobals = requestGlobals;
	}

	public void processResultValue(Object value) throws IOException {
		System.out
				.println("GwtComponentEventResultProcessor.processResultValue() value "
						+ value);
		System.out
				.println("GwtComponentEventResultProcessor.processResultValue() value.Class "
						+ value.getClass());

		// Is this a Default for GWT ?
		OutputStream os = requestGlobals.getResponse().getOutputStream("UTF-8");
		try {
			Method method =  ((RPCRequest) requestGlobals.getRequest().getAttribute(RPCRequest.class.getName())).getMethod();
			if (value instanceof GWTVoid || value instanceof GWTNull) {
				os.write(RPC.encodeResponseForSuccess(
						method, null).getBytes());
			} else if (value instanceof GWTBoolean) {
				os.write(RPC.encodeResponseForSuccess(
						method,
						((GWTBoolean) value).value).getBytes());
			} else {
				os.write(RPC.encodeResponseForSuccess(
						method, value).getBytes());
			}
		} catch (SerializationException e) {
			System.err.println(" SerializationException ");
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}
}
